# -*- coding: utf-8 -*-

from flask_restful import Resource, reqparse, fields, marshal_with, marshal, abort
from ..models import ServerRoom
from .. import db
from flask import jsonify

post_parser = reqparse.RequestParser()

post_parser.add_argument(
    'name', required=True, )

post_parser.add_argument(
    'address', required=True, )

post_parser.add_argument(
    'contacts', required=True, )

post_parser.add_argument(
    'contacts_tel', required=True, )

room_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'address': fields.String,
    'contacts': fields.String,
    'contacts_tel': fields.String
}


class Room(Resource):
    def get(self, id):
        server_room = ServerRoom.query.filter_by(id=id).first()
        if server_room is not None:
            return marshal(server_room, room_fields, envelope='data')
        else:
            resp = jsonify({'detail': 'Not found this serverRoom!'})
            resp.status_code = 400
            return resp

    def post(self):
        args = post_parser.parse_args()
        try:
            server_room = ServerRoom(name=args.name, address=args.address,
                                 contacts=args.contacts, contacts_tel=args.contacts_tel)
            db.session.add(server_room)
            db.session.commit()
            return marshal(server_room, room_fields)
        except:
            db.session.rollback()
            resp = jsonify({'detail': '出现错误，机房名称不能重复'})
            resp.status_code = 500
            return resp

    def put(self, id):
        args = post_parser.parse_args()
        server_room = ServerRoom.query.filter_by(id=id).first()
        if server_room is None:
            resp = jsonify({'detail': '更新出错，请刷新后重试！'})
            resp.status_code = 500
            return resp
        try:
            server_room.name = args.get('name', server_room.name)
            server_room.address = args.get('address', server_room.address)
            server_room.contacts = args.get('contacts', server_room.contacts)
            server_room.contacts_tel = args.get('contacts_tel', server_room.contacts_tel)
            db.session.add(server_room)
            db.session.commit()
            return marshal(server_room, room_fields)
        except:
            db.session.rollback()
            resp = jsonify({'detail': '出现错误，机房名称不能重复'})
            resp.status_code = 500
            return resp

    def delete(self, id):
        server_room = ServerRoom.query.filter_by(id=id).first()
        db.session.delete(server_room)
        return jsonify({'detail': 'success'})


class RoomList(Resource):
    def get(self):
        server_rooms = ServerRoom.query.all()
        return marshal(server_rooms, room_fields, envelope='data')
